using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using RollManager.Library.Utils;

namespace RollManager.Library.ActionSteps
{
    [Serializable]
    public class RebootStep : ActionStep
    {
        public int m_countdown = 20;
        public bool m_waitForService = false;

        [Description( "The coutdown of how many seconds to wait before rebooting the server." )]
        public int Countdown
        {
            get
            {
                return m_countdown;
            }
            set
            {
                m_countdown = value;
            }
        }


        [DisplayName( "Wait For Reboot" )]
        [Description( "Indicates whether the step should wait until the computer responds to pings again." )]
        public bool WaitForService
        {
            get
            {
                return m_waitForService;
            }
            set
            {
                m_waitForService = value;
            }
        }

        public override string Name
        {
            get { return "Reboot Server"; }
        }

        protected override void Run()
        {
            string command = Path.Combine( Common.PsToolsDir, "psshutdown.exe" );
            string args = string.Format( @"-r -f -t {0} \\{1}", m_countdown, CurrentServer );

            Common.RunCommand( command, args, Progress );

            if( !m_waitForService )
            {
                return;
            }

            Progress.Add( "Pinging server to wait for reboot." );

            // Wait until ping starts to fail.
            while( true )
            {
                if( PingStep.doPing(CurrentServer, Progress) == PingCondition.Failed )
                {
                    break;
                }
                Thread.Sleep( 1000 );
            }

            // Wait until ping starts to succeed.
            while( true )
            {
                if( PingStep.doPing( CurrentServer, Progress ) == PingCondition.Succeeded )
                {
                    break;
                }
            }

            Progress.Add( "Server pinging, waiting 5 seconds for good measure." );
            Thread.Sleep( 5000 );
        }

        protected override void Simulate()
        {
            Progress.AddFormat( "Simulated reboot of {0}", CurrentServer );
        }
    }
}
